﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace AndreySmirnov.BLToolkitUtils.VSPackage.Model.ViewModel
{
	public abstract class ViewModelBase : INotifyPropertyChanged
	{
		public event PropertyChangedEventHandler PropertyChanged;

		protected void NotifyPropertyChange(string propName)
		{
			PropertyChangedEventHandler handler = PropertyChanged;
			if (handler != null) handler(this, new PropertyChangedEventArgs(propName));
		}

		private static readonly Dictionary<Type, string[]> s_viewProperties
			= new Dictionary<Type, string[]>();

		private static string[] GetObjectProperties(Type t)
		{
			if (!s_viewProperties.ContainsKey(t))
			{
				lock(s_viewProperties)
				{
					if (!s_viewProperties.ContainsKey(t))
					{
						var props = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);
						s_viewProperties.Add(t, props.Select(x => x.Name).ToArray());
					}
				}
			}
			return s_viewProperties[t];
		}

		protected void NotifyAllPropsChanged()
		{
			foreach (var property in GetObjectProperties(GetType()))
			{
				NotifyPropertyChange(property);
			}
		}
	}
}
